import Big from "big.js";
Page<
  {
    list: Array<{
      id: number;
      name: string;
      price: number;
    }>;
    result: string[];
    totalMoney: number;
  },
  {
    onChange: (event: WechatMiniprogram.CustomEvent) => void;
    toggle: (event: WechatMiniprogram.CustomEvent) => void;
    noop: () => void;
  }
>({
  /**
   * 页面的初始数据
   */
  data: {
    list: [
      {
        id: 1,
        name: "商品A",
        price: 0.1,
      },
      {
        id: 2,
        name: "商品B",
        price: 0.2,
      },
    ],
    result: [],
    totalMoney: 0,
  },

  onChange(event: WechatMiniprogram.CustomEvent) {
    const result = event.detail as string[];
    const list = this.data.list;
    const totalMoney =
      result.reduce((previousValue, currentValue) => {
        let ret = new Big(previousValue);
        const goods = list.find((item) => item.id === parseInt(currentValue));
        if (goods) {
          ret = ret.add(goods.price);
        }
        return ret.toNumber();
      }, 0) * 100;
    // 之所以对 totalMoney 乘以 100，是因为 van-submit-bar 的 price 要求的值是 `分`
    console.log(totalMoney);
    this.setData({
      result,
      totalMoney,
    });
  },

  toggle(event: WechatMiniprogram.CustomEvent) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},
});
